package com.duqc.util;

import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import java.util.*;

/**
 * @ClassName CommonUtil
 * @Description todo
 * @Author duqc
 * @Date 2021/3/17
 **/
public class CommonUtil {

    /**
     * uuid 生成器
     *
     * @return uuid string
     */
    public static String uuidString() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    /**
     * 特殊字符转换  1^2^3   转换成 1,2,3
     *
     * @return
     */
    public static String conversion(String conversion) {
        if (conversion != null && conversion.length() > 1) {
            if (conversion.endsWith(",") || conversion.endsWith("^")) {
                conversion = conversion.substring(0, conversion.length() - 1);
            }
            conversion = conversion.replace("^", ",");
        }
        return conversion;
    }

    public static Map<String, Object> requireParameterToJson(String str) {
        Map<String, Object> map = new HashMap<>(16);
        String substring = str.substring(str.indexOf("("));
        String replace =
                substring.replace("(", "")
                        .replace(")", "");
        String[] splits = replace.split(",");
        for (String s : splits) {
            String[] strings = s.split("=");
            if (strings.length <= 1) {
                map.put(strings[0], null);
            } else {
                // fixme 该公共类如果需要获取集合类型的数据，需对 string[1] 进行类型校验，此处不需要处理集合数据
                map.put(strings[0], "null".equals(strings[1]) ? null : strings[1]);
            }
        }
        return map;
    }

    /**
     * 获取对象中为空的字段
     *
     * @param source 对象
     * @return 所有为空的字段数组
     */
    public static String[] getNullPropertyNames(Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet<>();
        for (java.beans.PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null || "".equals(srcValue)) {
                emptyNames.add(pd.getName());
            }
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }

}
